package keygen.server;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import com.sun.crypto.provider.SunJCE;

/**
 * 序列号生成类 采用Des算法生成激活序列号
 * 
 * @author duwenlong Date 2010-10-16
 */
public class DesKeyGenerator {

	public DesKeyGenerator(String signatureinfo) {
		// DESEncrypt(signatureinfo);
	}

	public static String DESEncrypt(String signatureinfo) {
		// 添加新安全算法 , 如果用 JCE 就要把它添加进去
		Security.addProvider(new SunJCE());
		String Algorithm = "DES"; // 定义 加密算法 , 可用 DES,DESede,Blowfish
		String encText = "";
		try {
			// 指定特定的密钥
			SecretKeyFactory keyFactory = SecretKeyFactory
					.getInstance(Algorithm);
			byte[] keyData = { 1, 9, 8, 2, 0, 8, 2, 1 };
			DESKeySpec keySpec = new DESKeySpec(keyData);
			Key key = keyFactory.generateSecret(keySpec);
			// 加密
			System.out
					.println("加密前的二进串 :" + byte2hex(signatureinfo.getBytes()));
			System.out.println("加密前的信息 :" + signatureinfo);
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.ENCRYPT_MODE, key);
			byte[] cipherByte = c1.doFinal(signatureinfo.getBytes());
			System.out.println("加密后的二进串 :" + byte2hex(cipherByte));
			encText = byte2hex(cipherByte);
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (Exception e3) {
			e3.printStackTrace();
		}
		return encText;
	}

	// 字节码转换成16进制字符串
	private static String byte2hex(byte bytes[]) {
		StringBuffer retString = new StringBuffer();
		for (int i = 0; i < bytes.length; ++i) {
			retString.append(Integer.toHexString(0x0100 + (bytes[i] & 0x00FF))
					.substring(1).toUpperCase());
		}
		return retString.toString();
	}

}
